<template>
	<view class="brightness-box">
		<view class="brightness-protection">
			<view style="margin-left: 20px;">护眼阅读模式</view>
			<switch :checked="comStore.iseffect" color="red" @change="switchChange"
				style="margin-right: 20px;transform:scale(0.7)" />
		</view>
		<view class="brightness-light">
			<text class="iconfont icon-liangdu1 liangdu0"></text>
			<view class="brightness-slider-container">
				<slider :min="0" :max="100" :step="1" :value="progress" @change="onSliderChange" show-value
					activeColor="#ff0307" backgroundColor="#bababa" />
			</view>
			<text class="iconfont icon-liangdu- liangdu0" style="margin-left: -20px;"></text>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onBeforeUnmount
	} from 'vue';
	import {
		useComStore
	} from '../../common/common';
	const progress = ref(0);
	const comStore = useComStore();
	
	// 保存原始亮度值，用于页面关闭时恢复
	const originalBrightness = ref(0);

	const switchChange = (e) => {
		// 根据uni-app事件处理规范修正事件值的获取方式
		comStore.iseffect = e.detail.value;
		console.log('护眼模式切换:', comStore.iseffect);
	}

	const onSliderChange = (e) => {
		const value = e.detail.value;
		progress.value = value;
		// 设置屏幕亮度，将0-100的值转换为0-1
		const brightness = value / 100;
		setBrightness(brightness);
	}
	
	// 设置屏幕亮度
	const setBrightness = (value) => {
		uni.setScreenBrightness({
			value: value,
			success: () => {
				console.log('设置屏幕亮度成功，当前亮度:', value);
			},
			fail: (err) => {
				console.error('设置屏幕亮度失败:', err);
			}
		});
	}
	
	// 获取当前屏幕亮度
	const getBrightness = () => {
		uni.getScreenBrightness({
			success: (res) => {
				// 保存原始亮度值
				originalBrightness.value = res.value;
				// 将0-1的值转换为0-100
				progress.value = Math.round(res.value * 100);
				console.log('获取屏幕亮度成功，当前亮度:', res.value);
			},
			fail: (err) => {
				console.error('获取屏幕亮度失败:', err);
			}
		});
	}

	
	onBeforeUnmount(() => {
		// 页面卸载时恢复原始亮度
		if (originalBrightness.value > 0) {
			setBrightness(originalBrightness.value);
		}
	});

	onMounted(() => {
		// 获取当前屏幕亮度
		getBrightness();

	});
</script>

<style lang="scss">
	.brightness-box {
		position: absolute;
		bottom: 0px;
		width: 100vw;
		height: 180px; // 增加高度以容纳电池信息
		background-color: var(--bg-color);

		.brightness-protection {
			width: 100%;
			height: 70px;
			display: flex;
			justify-content: space-between;
			align-items: center;
			color: #fff;
			font-size: 16px;
		}

		.brightness-light {
			width: 100%;
			height: 70px;
			display: flex;
			align-items: center;
			justify-content: center;

			.brightness-slider-container {
				width: 80%;
			}

			.liangdu0 {
				font-size: 24px;
			}

			.liangdu1 {
				font-size: 24px;
			}
		}

		.battery-info {
			width: 100%;
			height: 40px;
			display: flex;
			justify-content: center;
			align-items: center;
			color: #fff;
			font-size: 14px;
			
			.battery-text {
				margin-right: 10px;
			}
			
			.battery-status {
				font-size: 12px;
				opacity: 0.8;
			}
		}
	}
</style>